package com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap;

import com.alibaba.cirtus.ots.application.adapter.ability.model.request.FactoryPsRequest;
import com.alibaba.cirtus.ots.application.adapter.ability.model.request.ProduceSchedulingDTO;
import com.alibaba.cirtus.ots.application.adapter.ability.model.request.ProduceSchedulingRequest;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.HttpTokenUtil;
import com.alibaba.cirtus.ots.application.adapter.ability.utils.HttpUtils;
import com.alibaba.citrus.ots.common.annotation.ProcessInvoker;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.otsapplicationadaptersdk.contants.OtsApplicationAdapterSdkConstants;
import com.epoch.app.otsapplicationadaptersdk.mnsapiffactoryps.service.MnSapIfFactoryPsService;
import com.epoch.app.otsapplicationadaptersdk.model.dto.IntegrationFactoryOutputRequest;
import com.epoch.app.otsapplicationadaptersdk.model.dto.IntegrationProduceSchedulingRequest;
import com.epoch.app.otsapplicationadaptersdk.model.dto.SapFactoryOutputDTO;
import com.epoch.app.otsapplicationadaptersdk.model.dto.SapFactoryOutputResp;
import com.epoch.app.otsapplicationadaptersdk.model.dto.SapProduceSchedulingDTO;
import com.epoch.app.otsapplicationadaptersdk.model.dto.SapProduceSchedulingResp;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author
 * @Description sap请求中台同步工厂排产量
 * @date 2024/4/26
 */
@Component
public class MnSapIfFactoryPsServiceImpl implements MnSapIfFactoryPsService {
    private static final Logger log = LoggerFactory.getLogger(MnSapIfFactoryPsServiceImpl.class);
    private static final String integrationFactoryPs_URL = "/api/omni_application_adapter_sdk/sap_create_factory_ps";
    private static final String integrationProduceScheduling_URL = "/api/omni_application_adapter_sdk/sap_sync_produce_scheduling";
    private static final String OPERATOR_CODE = "SYSTEM";

    @Autowired
    private HttpUtils httpUtils;

    @Override
    @ProcessInvoker(remark = "integrationFactoryPs", errorCode = "OTS-02-007-00-16-999", printLog = true)
    public Result<List<SapFactoryOutputResp>> integrationFactoryPs(IntegrationFactoryOutputRequest integrationFactoryOutputRequest) {
        Result<List<SapFactoryOutputResp>> result = new Result<>();
        try {
            Map<String, String> header = HttpTokenUtil.generateHttpHeader();
            List<SapFactoryOutputDTO> reqList = integrationFactoryOutputRequest.getReqList();
            if (CollectionUtils.isNotEmpty(reqList)) {
                String url = OtsApplicationAdapterSdkConstants.urlPrefix() + integrationFactoryPs_URL;
                FactoryPsRequest body = new FactoryPsRequest();
                body.setReqList(reqList);
                ResponseEntity<Result> resEntity = httpUtils.post(url, header, body, Result.class);
                log.info("integrationFactoryOutput_resEntity:{}", JSONObject.toJSONString(resEntity));
                if (resEntity != null && resEntity.getBody() != null) {
                    List<SapFactoryOutputResp> resList = (List<SapFactoryOutputResp>) resEntity.getBody().getResult();
                    result.setResult(resList);
                    result.setTotal(resEntity.getBody().getTotal());
                    result.setSuccess(resEntity.getBody().isSuccess());
                }
            }else{
                result.setMessage("同步数据为空");
            }
        } catch (Exception e) {
            log.error("integrationFactoryOutput_error", e);
            e.printStackTrace();
        }
        return result;
    }

    @Override
    @ProcessInvoker(remark = "integrationProduceScheduling", errorCode = "OTS-02-007-00-16-999", printLog = true)
    public Result<List<SapProduceSchedulingResp>> integrationProduceScheduling(IntegrationProduceSchedulingRequest integrationProduceSchedulingRequest) {
        Result<List<SapProduceSchedulingResp>> result = new Result<>();
        try {
            Map<String, String> header = HttpTokenUtil.generateHttpHeader();
            List<SapProduceSchedulingDTO> reqList = integrationProduceSchedulingRequest.getItems();
            if (CollectionUtils.isNotEmpty(reqList)) {
                String url = OtsApplicationAdapterSdkConstants.urlPrefix() + integrationProduceScheduling_URL;
                ProduceSchedulingRequest body = new ProduceSchedulingRequest();
                List<ProduceSchedulingDTO> dataList = reqList.stream().map(x->{
                    ProduceSchedulingDTO dto = new ProduceSchedulingDTO();
                    dto.setScheduledDate(x.getDFF1());
                    dto.setFactoryCode(x.getDFF2());
                    dto.setProductCode(x.getDFF3());
                    dto.setProductName(x.getDFF4());
                    dto.setPlannedQuantity(StringUtils.isNotBlank(x.getZJHSL())?new BigDecimal(x.getZJHSL().trim()).intValue():null);
                    dto.setInputWarehouseData(x.getBUDAT());
                    dto.setOutputQuantity(StringUtils.isNotBlank(x.getWEMNG())?new BigDecimal(x.getWEMNG().trim()).intValue():null);
                    dto.setOperator(OPERATOR_CODE);
                    return dto;
                }).collect(Collectors.toList());
                body.setReqList(dataList);
                ResponseEntity<Result> resEntity = httpUtils.post(url, header, body, Result.class);
                log.info("integrationProduceScheduling_resEntity:{}", JSONObject.toJSONString(resEntity));
                if (resEntity != null && resEntity.getBody() != null) {
                    List<SapProduceSchedulingResp> response = new ArrayList<>();
                    for (Object o : (List)resEntity.getBody().getResult()) {
                        ProduceSchedulingDTO dto = new ProduceSchedulingDTO();
                        try {
                            BeanUtils.populate(dto, (Map) o);
                        } catch (Exception e) {
                            log.error("integrationProduceScheduling_populate_error", e);
                        }
                        SapProduceSchedulingResp resp = new SapProduceSchedulingResp();
                        resp.setDFF1(dto.getScheduledDate());
                        resp.setDFF2(dto.getFactoryCode());
                        resp.setDFF3(dto.getProductCode());
                        resp.setDFF4(dto.getProductName());
                        resp.setZJHSL(dto.getPlannedQuantity()!=null?dto.getPlannedQuantity().toString():null);
                        resp.setBUDAT(dto.getInputWarehouseData());
                        resp.setWEMNG(dto.getOutputQuantity()!=null?dto.getOutputQuantity().toString():null);
                        resp.setErrorMessage(dto.getErrorMessage());
                        response.add(resp);
                    }
                    result.setResult(response);
                    result.setTotal(resEntity.getBody().getTotal());
                    result.setSuccess(resEntity.getBody().isSuccess());
                }
            }else{
                result.setMessage("同步数据为空");
            }
        } catch (Exception e) {
            log.error("integrationProduceScheduling_error", e);
            e.printStackTrace();
        }
        return result;
    }



}
